package com.example.vote.controller;

import org.springframework.core.convert.converter.Converter;

import java.time.LocalDate;
import java.time.format.DateTimeParseException;

public class LocalDateConvertor implements Converter<String, LocalDate> {

    @Override
    public LocalDate convert(String source) {
        String regex = "(\\d{4})[/\\-](\\d{1,2})[/\\-](\\d{1,2}) .+";
        if (source.matches(regex)) {
            String s1 = source.replaceAll(regex, "$1");
            String s2 = source.replaceAll(regex, "$2");
            String s3 = source.replaceAll(regex, "$3");
            int year = Integer.parseInt(s1);
            int month = Integer.parseInt(s2);
            int days = Integer.parseInt(s3);
            final LocalDate date = LocalDate.of(year, month, days);
            return date;
        } else {
            throw new DateTimeParseException("日期格式错误", source, -1);
        }
    }
}
